Page({
  data: {
    dialogVisible: false,
    houseList: [],
    isEmpty: false,
  },
  onShow() {
    // 获取用户房屋列表
    this.getHouseList()
  },
  async getHouseList() {
    const { code, data: houseList } = await wx.http.get('/room')
    if (code !== 10000) return wx.utils.toast('获取房屋列表数据失败')
    this.setData({
      houseList,
      isEmpty: houseList.length === 0,
    })
  },
  async deleteHouse() {
    if (!this.cellId) return wx.utils.toast('参数有误')
    // 调用接口
    const { code } = await wx.http.delete(`/room/${this.cellId}`)
    // 检测接口是否调用成功
    if (code !== 10000) return wx.utils.toast('删除房屋失败')
    this.data.houseList.splice(this.cellIndex, 1)
    this.setData({
      houseList: this.data.houseList,
      isEmpty: this.data.houseList.length === 0,
    })
    // // 删除成功，刷新列表
    // this.getHouseList()
  },

  swipeClose(ev) {
    const { position, instance } = ev.detail

    if (position === 'right') {
      // 显示 Dialog 对话框
      this.setData({
        dialogVisible: true,
      })
      // 记录房屋的id 和索引，在调用接口时使用
      this.cellId = ev.mark.id
      this.cellIndex = ev.mark.index
      // console.log(ev)
      // swiper-cell 滑块关闭
      instance.close()
    }
  },
  dialogClose(ev) {
    // console.log(ev.detail)
    // 当用户点击删除按钮时删除数据
    if (ev.detail=== 'confirm') this.deleteHouse()
  },

  goDetail(ev) {
    wx.navigateTo({
      url: '/house_pkg/pages/detail/index?id=' + ev.mark.id,
    })
  },

  addHouse() {
    wx.navigateTo({
      url: '/house_pkg/pages/locate/index',
    })
  },
})
